/**
 * request utils
 */
let responseJsonUtils = require('../utils/responseJsonUtils.js');
let errinfo = require('../errinfo.js');

let requestUtils = module.exports = {};

let ObjectId = mongoose.Types.ObjectId;


requestUtils.getRequestAddress = function (req) {

    req.connection = req.connection || {};
    req.socket = req.socket || {};
    req.connection.socket = req.connection.socket || {};

    return req.headers['x-forwarded-for'] ||
        req.connection.remoteAddress ||
        req.socket.remoteAddress ||
        req.connection.socket.remoteAddress;
};
// page parameter
requestUtils.page = function (req, data) {
    // page number, start with 1
    data = data || {};
    let pageNo = parseInt(req.query.page);
    if (!isNaN(pageNo)) {
        if (pageNo < 1) {
            pageNo = 1;
        }
    } else {
        pageNo = 1;
    }
    // current page
    data.currentPage = pageNo;
    req.pageNo = pageNo;

    return data;
};
requestUtils.getResourceDocument = function (req, res, next) {
    if (!req.resourceModelName || !req.resourceId) {
        next();
        return;
    }

    global[req.resourceModelName].findOne({_id: new ObjectId(req.resourceId)})
        .exec(function (err, resourceResult) {
            if (err) {
                next(responseJsonUtils.json(errinfo.mongodb.internalError, err));
                return;
            }
            req.resourceDocument = resourceResult;
            next();
        });
};
